package com.wyz.note.project.auth.core.config.security;

import com.alibaba.fastjson.JSON;
import com.wyz.note.project.auth.common.enums.ResultCode;
import com.wyz.note.project.auth.core.base.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author: wei yz
 * @Date: 2022/6/21 8:54
 */
public class NoteAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private static final Logger log = LoggerFactory.getLogger(NoteAuthenticationFailureHandler.class);

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.error("===========登录失败===========");
        log.error("==> 原因：{}", exception.getMessage());
        String message;
        if (exception instanceof BadCredentialsException || exception instanceof UsernameNotFoundException) {
            message = "账户名或者密码输入错误!";
        } else if (exception instanceof LockedException) {
            message = "账户被锁定，请联系管理员!";
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码过期，请联系管理员!";
        } else if (exception instanceof AccountExpiredException) {
            message = "账户过期，请联系管理员!";
        } else if (exception instanceof DisabledException) {
            message = "账户被禁用，请联系管理员!";
        } else if (exception instanceof InsufficientAuthenticationException) {
            message = exception.getMessage();
        } else {
            message = "登录失败!";
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(
                JSON.toJSONString(new Result()
                        .setSuccess(false)
                        .setCode(ResultCode.UNAUTHORIZED)
                        .setMessage(message)));
    }
}
